package com.ewhl.mark.meijialian;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebHistoryItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;


import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CommonWebActivity extends AppCompatActivity {


    private static final String TAG = "SRG";
    private static final long EXPIRE_TIME = 1000;
    private static final int REQ_CALL_PERMISSION = 111;
    private static final int REQ_LOCATION_PERMISSION = 222;

    private long firstTime = 0;
    public static int load = 0;
    public static boolean isForeground = false;
    @BindView(R.id.wv_content)
    WebView webContent;
    private LocationService locationService;
    private ValueCallback<Uri> mUploadMessage;// 表单的数据信息
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;   
    private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调</span>
    private Uri imageUri;

    String loadUrl;
    String current_url="";
    String ahead_url="";
    View content;
    Map<String,String> extraHeaders;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
                        | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_web);
        locationService = MjlApplication.locationService;
        locationService.registerListener(mListener);//是否应
//        AndroidBug5497Workaround.assistActivity(this);//兼容沉浸式
        ButterKnife.bind(this);
        content=findViewById(android.R.id.content);
//        content.getViewTreeObserver().addOnGlobalLayoutListener(this);
        loadUrl=getIntent().getStringExtra("load_url");
        current_url=loadUrl;
        initView();

//        StatusBarUtil.setColor(this,getResources().getColor(R.color.colorAccent));
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE| WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }

    private BDLocationListener mListener = new BDLocationListener() {

        @TargetApi(Build.VERSION_CODES.KITKAT)
        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            Double lat=location.getLatitude();
            Double lng=location.getLongitude();
//            NumberFormat numberFormat=NumberFormat.getNumberInstance();
//            numberFormat.setGroupingUsed(false);
//                Log.d("location",location.getCity());
                 webContent.evaluateJavascript("javascript:refresh_local('"+location.getCity()+"','"+location.getDistrict()+"')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });


//            }


        }


    };


    @Override
    protected void onPause() {
        super.onPause();
        locationService.stop();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        locationService.stop(); // 停止定位服务
        super.onStop();
    }



    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------

        // 获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的

        // 注册监听
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());

    }
    @SuppressLint("JavascriptInterface")
    public void initView() {



//        String versionName = ExampleUtil.GetVersion(getApplicationContext());
        extraHeaders = new HashMap<String, String>();
        extraHeaders.put("Referer", "http://chengjing.cnewhl.com");

        if(CommonUtils.checkNull(loadUrl)){
            webContent.loadUrl(loadUrl,extraHeaders);//加载url
        }

        //使用webview显示html代码
//        webContent.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>" +
//                "<body><h2>使用webview显示 html代码</h2></body></html>", "text/html" , "utf-8", null);
        webContent.getSettings().setJavaScriptEnabled(true);
        webContent.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webContent.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        webContent.setWebChromeClient(webChromeClient);
        webContent.setWebViewClient(webViewClient);
        WebSettings webSettings = webContent.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webContent.getSettings().setAllowFileAccessFromFileURLs(true);
        }
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        //②将object对象暴露给Js,调用addjavascriptInterface
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        webSettings.supportMultipleWindows();
        webSettings.setAllowFileAccess(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);

        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(false);
        //不显示webview缩放按钮
//        webSettings.setDisplayZoomControls(false);


    }

    @JavascriptInterface
    public void back() {
            finish();
    }
    @JavascriptInterface
    public void goto_shop(){
        if (ActivityCompat.checkSelfPermission(CommonWebActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "请先开启位置权限", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(CommonWebActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQ_LOCATION_PERMISSION);


        }else {
            CommonUtils.startActivity(this,ShopMapActivity.class);
        }

    }
    @JavascriptInterface
    public void goto_share() {
        onBackPressed();
    }

    @JavascriptInterface
    public void sub_action(String id) {

    }
    @JavascriptInterface
    public void share(String title, String text, String img, String url){
        CommonUtils.share(this,title,text,img,url);
    }

    @JavascriptInterface
    public void goto_login() {

        CommonUtils.goToWeb(this,LoginActivity.class,current_url);
        Log.d("login_url",current_url);
    }
    @JavascriptInterface
    public void goto_logout() {
        SPUtils.put(CommonWebActivity.this,"key","");
        CommonUtils.startActivity(this,LoginActivity.class);
        finish();
    }
    @JavascriptInterface
    public void save_token(String key) {
        SPUtils.put(CommonWebActivity.this,"key",key);
      CommonUtils.destoryActivity();

    }
    @Override
    public void onBackPressed() {
        Log.d("back","back");
    }

    private String telurl;
    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成

            super.onPageFinished(view,url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载


        }

        @Override
        public boolean shouldOverrideUrlLoading
                (WebView view, String url) {
            Log.i("用户单击超连接", url);
            //判断用户单击的是那个超连接
            current_url=url;
            String tag = "tel:";
            Log.d("url",url);
            final Activity context = CommonWebActivity.this;
            if (url.contains("platformapi/startapp")) {
                startAlipayActivity(url);
                return true;
            }else if ((Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
                    && (url.contains("platformapi") && url.contains("startapp"))) {
                startAlipayActivity(url);
                return true;
            }
            // ------  对alipays:相关的scheme处理 -------
            if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                try {
                    context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                } catch (Exception e) {
                    try {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    } catch (Exception e1) {
//                        view.loadUrl(url);
                    }
                }

                return true;
            }



            // ------- 处理结束 -------

            // ------  对alipays:相关的scheme处理 -------
            if (url.startsWith("weixin:") || url.startsWith("weixin")) {
                try {
                    context.startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                } catch (Exception e) {
                    try {
                        new AlertDialog.Builder(context)
                                .setMessage("未检测到微信客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("http://dldir1.qq.com/weixin/android/weixin667android1320.apk");
                                        context.startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    } catch (Exception e1) {
//                        view.loadUrl(url);
                    }
                }

                return true;
            }
            // ------- 处理结束 -------


            if (url.startsWith("tel:")) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_CALL, uri);
                if (ActivityCompat.checkSelfPermission(CommonWebActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(CommonWebActivity.this, new String[]{Manifest.permission.CALL_PHONE}, REQ_CALL_PERMISSION);
                    telurl=url;
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return true;
                }
                startActivity(intent);
                //这个超连接,java已经处理了，webview不要处理了
                return true;
            }
//            if (!(url.startsWith("http") || url.startsWith("https"))) {
//                return true;
//            }
            view.loadUrl(url,extraHeaders);
            return true;
        }


    };

    @SuppressLint("MissingPermission")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_CALL_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // User agree the permission
                    Uri uri = Uri.parse(telurl);
                    Intent intent = new Intent(Intent.ACTION_CALL, uri);
                    startActivity(intent);
                } else {
                    // User disagree the permission
                    Toast.makeText(this, "请先开启打电话权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    private void startAlipayActivity(String url) {

        Intent intent;
        try {
            intent = Intent.parseUri(url,
                    Intent.URI_INTENT_SCHEME);
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setComponent(null);
            startActivity(intent);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getLastUrl(){
        try {
            WebBackForwardList backForwardList = webContent.copyBackForwardList();
            if (backForwardList != null && backForwardList.getSize() != 0) {
                //当前页面在历史队列中的位置
                int currentIndex = backForwardList.getCurrentIndex();
                WebHistoryItem historyItem =
                        backForwardList.getItemAtIndex(currentIndex - 1);
                if (historyItem != null) {
                    String backPageUrl = historyItem.getUrl();
//                Logger.t("111").d("拿到返回上一页的url"+backPageUrl);
                    return backPageUrl;
                }
                return loadUrl;
            }
        }catch (Exception e){
            return loadUrl;
        }

        return loadUrl;

    }

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        @Override
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = filePathCallback;
            take();
//            onenFileChooseImpleForAndroid(filePathCallback);
            return true;
        }


        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            take();
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooserImpl(uploadMsg);

        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            take();
        }


        //        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen", "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen", "是否有上一个页面:" + webContent.canGoBack());
        if (webContent.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webContent.goBack(); //
            return true;
        } else {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode) {

            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒，则不退出
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {
//                    MobclickAgent.onKillProcess(this);
                    //两次按键小于2秒时，退出应用
//                    Intent home = new Intent(Intent.ACTION_MAIN);
//                    home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    home.addCategory(Intent.CATEGORY_HOME);
//                    startActivity(home);
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }


    /**
     * JS调用android的方法
     *
     * @param
     * @return
     */
    @JavascriptInterface //仍然必不可少
    public void bindDevice(int id) {
//        Toast.makeText(this, "html调用客户端  userid:" + id, Toast.LENGTH_SHORT).show();
        Log.i("ansen", "html调用客户端:" + id);
    }


    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onResume() {
        if(CommonUtils.checkNull((String) SPUtils.get(this,"key",""))){
            Log.d("srg","CAREATE_SESSION");
            webContent.evaluateJavascript("javascript:create_session('"+SPUtils.get(this,"key","")+"')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.d("srg","CAREATE_SESSION111");
                }
            });
        }
        if(isForeground){
            webContent.reload();
            webContent.onResume();
            isForeground=false;
        }
        locationService.start();
        super.onResume();
    }


    @Override
    public void onDestroy() {

        super.onDestroy();
        webContent.destroy();

        webContent = null;
        locationService.unregisterListener(mListener); // 注销掉监听
        locationService.stop();
    }


    //for receive customer msg from jpush server


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {

                if (result != null) {
                    String path = getPath(getApplicationContext(),
                            result);
                    Uri uri = Uri.fromFile(new File(path));
                    mUploadMessage
                            .onReceiveValue(uri);
                } else {
                    mUploadMessage.onReceiveValue(imageUri);
                }
                mUploadMessage = null;


            }
        } else if(requestCode ==FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5) {
             Uri result = (data == null || resultCode != Activity.RESULT_OK) ? null: data.getData();
                 if (null == mUploadCallbackAboveL)
                   return;

            if (result != null) {
                 mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                   } else {


                mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
                mUploadCallbackAboveL = null;
            }
        }
    }

    @SuppressWarnings("null")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != FILECHOOSER_RESULTCODE
                || mUploadCallbackAboveL == null) {
            return;
        }

        Uri[] results = null;

        if (resultCode == Activity.RESULT_OK) {

            if (data == null) {

                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();

                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        if (results != null) {
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        } else {
            results = new Uri[]{imageUri};
            mUploadCallbackAboveL.onReceiveValue(results);
            mUploadCallbackAboveL = null;
        }

        return;
    }

    private void take() {
        File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
        // Create the storage directory if it does not exist
        if (!imageStorageDir.exists()) {
            imageStorageDir.mkdirs();
        }
        File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        imageUri = Uri.fromFile(file);

        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for (ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent i = new Intent(captureIntent);
            i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
            i.setPackage(packageName);
            i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            cameraIntents.add(i);

        }
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
        CommonWebActivity.this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
    }

    @SuppressLint("NewApi")
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null) cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    private void onenFileChooseImpleForAndroid(ValueCallback<Uri[]> filePathCallback) {

        mUploadCallbackAboveL = filePathCallback;
        Intent contentSelectionIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        contentSelectionIntent.setType("image/*");
        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(chooserIntent, FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5);

    }




}
